package com.gomore.opple.module.login;

import android.text.TextUtils;

import com.gomore.opple.R;
import com.gomore.opple.data.DataRepository;
import com.gomore.opple.data.remote.retrofit.HttpResponseFunc;
import com.gomore.opple.data.remote.retrofit.RxSubscriber;
import com.gomore.opple.data.remote.retrofit.ServerResponseFunc;
import com.gomore.opple.exception.ApiException;
import com.gomore.opple.rest.employee.LoginInfo;
import com.gomore.opple.rest.employee.LoginResult;
import com.gomore.opple.rest.employee.ResetPasswordRequest;
import com.gomore.opple.web.cgform.app.entity.TOAppversionEntity;

import javax.inject.Inject;

import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import rx.subscriptions.CompositeSubscription;

public class LoginPresenter implements LoginContract.Presenter {

    private DataRepository mDataRepositroy;
    private final LoginContract.View mView;
    private CompositeSubscription mSubscriptions;

    @Inject
    LoginPresenter(DataRepository dataRepository, LoginContract.View view) {
        mDataRepositroy = dataRepository;
        mView = view;
        mSubscriptions = new CompositeSubscription();
        mView.setPresenter(this);
    }


    @Override
    public void subscribe() {

    }

    @Override
    public void unsubscribe() {
        mSubscriptions.clear();
    }

    /**
     * 登录
     *
     * @param username 用户名
     * @param password 密码
     */
    @Override
    public void login(final String username, final String password) {
        if (TextUtils.isEmpty(username)) {
            mView.showMessage(R.string.hint_name_empty);
            return;
        } else if (TextUtils.isEmpty(password)) {
            mView.showMessage(R.string.hint_password_empty);
            return;
        }
        unsubscribe();
        mView.showProgressDialog();
        LoginInfo loginInfo = new LoginInfo();
        loginInfo.setUsername(username);
        loginInfo.setPassword(password);
        Subscription subscription = mDataRepositroy.login(loginInfo)
                //map --> 操作符(Operators)：解决对Observable对象的变换的问题
                .map(new ServerResponseFunc<LoginResult>())
                .onErrorResumeNext(new HttpResponseFunc<LoginResult>())
                //使用subscribeOn()指定观察者代码运行的线程
                .subscribeOn(Schedulers.io())
                //  AndroidSchedulers提供了针对Android的线程系统的调度器    使用observerOn()指定订阅者运行的线程
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new RxSubscriber<LoginResult>() {
                    @Override
                    public void onNext(LoginResult loginResult) {
                        super.onNext(loginResult);
                        mView.hideProgressDialog();
                        //保存用户登录成功之后的信息
                        mDataRepositroy.saveUser(loginResult);
                        //保存用户名密码
                        mDataRepositroy.saveUserName(username);
                        mDataRepositroy.savePassWord(password);
                        mView.gotoMainActivity();
                    }

                    @Override
                    protected void onError(ApiException ex) {
                        ex.printStackTrace();
                        mView.hideProgressDialog();
                        mView.showMessage(ex.message);
                    }
                });
        mSubscriptions.add(subscription);
    }

    /**
     * 检查更新
     *
     * @param apptype app类型
     */
    @Override
    public void checkUpdate(String apptype, String version) {
        unsubscribe();
        mView.showProgressDialog();
        Subscription subscription = mDataRepositroy.checkUpdate(apptype, version)
                .map(new ServerResponseFunc<TOAppversionEntity>())
                .onErrorResumeNext(new HttpResponseFunc<TOAppversionEntity>())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new RxSubscriber<TOAppversionEntity>() {
                    @Override
                    public void onNext(TOAppversionEntity version) {
                        super.onNext(version);
                        mView.hideProgressDialog();
                        mView.showUpdateDialog(version);
                    }

                    @Override
                    protected void onError(ApiException ex) {
                        mView.hideProgressDialog();
                    }
                });
        mSubscriptions.add(subscription);
    }

    /**
     * 初始化数据
     */
    @Override
    public void prepareInitData() {
        if (mDataRepositroy.getUserName() != null &&
                mDataRepositroy.getPassWord() != null) {
            mView.initView(mDataRepositroy.getUserName(), mDataRepositroy.getPassWord());
        }
    }

    @Override
    public void sendCode(String mobilephone, String username) {
        unsubscribe();
        mView.showProgressDialog();
        Subscription subscription = mDataRepositroy.sendCode(mobilephone, username)
                .map(new ServerResponseFunc<String>())
                .onErrorResumeNext(new HttpResponseFunc<String>())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new RxSubscriber<String>() {
                    @Override
                    public void onNext(String version) {
                        super.onNext(version);
                        mView.hideProgressDialog();
                        mView.showMessage(R.string.send_code_success);
                    }

                    @Override
                    protected void onError(ApiException ex) {
                        mView.hideProgressDialog();
                        mView.showMessage(R.string.send_code_success);
                    }
                });
        mSubscriptions.add(subscription);
    }

    @Override
    public void resetPassword(String username, String smsCode, String newPassword) {
        unsubscribe();
        mView.showProgressDialog();
        ResetPasswordRequest resetPasswordRequest = new ResetPasswordRequest();
        resetPasswordRequest.setUsername(username);
        resetPasswordRequest.setSmsCode(smsCode);
        resetPasswordRequest.setNewPassword(newPassword);
        Subscription subscription = mDataRepositroy.restPassword(resetPasswordRequest)
                .map(new ServerResponseFunc<String>())
                .onErrorResumeNext(new HttpResponseFunc<String>())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new RxSubscriber<String>() {
                    @Override
                    public void onNext(String version) {
                        super.onNext(version);
                        mView.hideProgressDialog();
                        mView.showMessage(R.string.reset_success);
                        mView.goToLogin();
                    }

                    @Override
                    protected void onError(ApiException ex) {
                        mView.hideProgressDialog();
                        mView.showMessage(R.string.reset_fail);
                    }
                });
        mSubscriptions.add(subscription);
    }

}
